/**
 * 不同于项目内部的http请求
 * 比较干净，不从cookies里面取token、不拦截返回值
 * 可在 config 里面重写 baseURL
 * created: YJ
 * date: 20100306
 */

import axios from 'axios'
import qs from 'qs'
import isPlainObject from 'lodash/isPlainObject'
import $cookies from '@/utils/cookies.js'

const httpm = axios.create({
  baseURL: window.SITE_CONFIG['apiURL'],
  timeout: 1000 * 180,
  withCredentials: true
})

/**
 * 请求拦截
 */
httpm.interceptors.request.use(config => {
  config.headers['Accept-Language'] = $cookies.get('language') || 'zh-CN'
  config.headers['token'] = config.headers['token'] || new Date().getTime()
  // 默认参数
  var defaults = {}
  // 防止缓存，GET请求默认带_t参数
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      ...{ '_t': new Date().getTime() }
    }
  }
  if (isPlainObject(config.params)) {
    config.params = {
      ...defaults,
      ...config.params
    }
  }
  if (isPlainObject(config.data)) {
    config.data = {
      ...defaults,
      ...config.data
    }
    if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
      config.data = qs.stringify(config.data)
    }
  }
  return config
})

/**
 * 响应拦截
 */
httpm.interceptors.response.use(response => {
  return response
})

export default httpm
